package org.yray.initializer;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;

@Slf4j
public class NacosInitializer implements EnvironmentPostProcessor, Ordered {

    String NACOS_PREFIX = "spring.cloud.nacos.config";
    String NACOS_BOOTSTRAP_PROPERTY_SOURCE_NAME = "NacosBootstrapPropertySources";
    private static final String[] NACOS_SYSTEM_PROPERTIES = {
            "spring.cloud.nacos.config.group",
            "spring.cloud.nacos.config.name"};
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication application) {
        log.info("NacosInitializer");
//        initializeSystemProperty(configurableEnvironment);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    void initializeSystemProperty(ConfigurableEnvironment environment) {
        NacosConfigProperties nacosConfigProperties=fillSystemPropertyFromEnvironment(environment);
        nacosConfigProperties.setEnvironment(environment);
        NacosConfigManager nacosConfigManager=new NacosConfigManager(nacosConfigProperties);
        NacosPropertySourceLocator nacosPropertySourceLocator=new NacosPropertySourceLocator(nacosConfigManager);
        nacosPropertySourceLocator.locate(environment);
        CompositePropertySource composite = new CompositePropertySource(NACOS_BOOTSTRAP_PROPERTY_SOURCE_NAME);


        environment.getPropertySources().addFirst(composite);
    }

    private NacosConfigProperties fillSystemPropertyFromEnvironment(ConfigurableEnvironment environment) {
        NacosConfigProperties nacosConfigProperties=new NacosConfigProperties();

        for (String propertyName:NACOS_SYSTEM_PROPERTIES) {
            String propertyValue = environment.getProperty(propertyName);
            System.setProperty(propertyName, propertyValue);
            String tempClassPropertyName = propertyName.substring(NACOS_PREFIX.length()+1);
            String[] classPropertyNames=tempClassPropertyName.split("\\.");
            ReflectionUtil.setFieldValue(nacosConfigProperties,classPropertyNames,propertyValue);
        }
        //
        String propertyValue = environment.getProperty("spring.cloud.nacos.server-addr");
        System.setProperty("spring.cloud.nacos.server-addr", propertyValue);
        nacosConfigProperties.setServerAddr(propertyValue);
        return nacosConfigProperties;
    }
}
